package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.view.View;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.ddm.app.AppConst;
import com.dindang.ddm.mvp.contract.BacklogContract;
import com.dindang.ddm.mvp.model.entity.Backlog;
import com.dindang.ddm.mvp.model.entity.BaseResponse;
import com.dindang.ddm.mvp.ui.adapter.multitype.BacklogViewBinder;
import com.dindang.ddm.mvp.ui.widget.AddProgressDialog;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.model.LoginEvent;
import com.longxi.gamer_base.model.MaintainDetailsEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@FragmentScope
public class BacklogPresenter extends BasePresenter<BacklogContract.Model, BacklogContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private boolean isFirst = true;
    private MultiTypeAdapter mAdapter;
    private Items mItems = new Items();
    private int LIMIT = 10;
    private Backlog.ToDoParam mParam = new Backlog.ToDoParam();

    @Inject
    public BacklogPresenter(BacklogContract.Model model, BacklogContract.View rootView) {
        super(model, rootView);
    }

    public void initView() {
        mRootView.getToolbarTitle().setText("待办");
        initAdapter();
    }

    public void initListener() {
        initPtrFrame();
    }

    public void initDate() {
        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        if(isFirst){
            LogUtils.debugInfo("Backlog页面重新加载");
            isFirst = false;
            isLogin();
        }
    }

    private void initAdapter() {
        if(mAdapter == null){
            mAdapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            mAdapter.register(Backlog.ToDo.Rows.class, new BacklogViewBinder().setListener(new BacklogViewBinder.OnClickListener() {
                @Override
                public void onClick(int position) {
                    Backlog.ToDo.Rows todo = (Backlog.ToDo.Rows) mItems.get(position);
//                    Intent intent = ARouter.getInstance().build("/maintenance/activity/MaintainDetailsActivity").withString("id", todo.l_id).navigation(mRootView.getFragment().getActivity(), AppConst.IntentRequstCode.ACTIVITY_LOGIN);
                    Postcard postcard = ARouter.getInstance().build("/maintenance/activity/MaintainDetailsActivity");
                    LogisticsCenter.completion(postcard);
                    Class<?> destination = postcard.getDestination();
                    Intent intent = new Intent(mAppManager.getCurrentActivity(),destination);
                    intent.putExtra("id", todo.l_id);
                    mRootView.getFragment().startActivityForResult(intent,AppConst.IntentRequstCode.ACTIVITY_MaintainDetails);
                }

                @Override
                public void onProgress(int position) {
                    dialogProgress();
                }

                @Override
                public void onUndo(int position) {

                }

                @Override
                public void onOrder(int position) {

                }

                @Override
                public void onPlan(int position) {
                    ARouter.getInstance().build("/maintenance/activity/PlanActivity").navigation();
                }

                @Override
                public void onComplete(int position) {
                    ARouter.getInstance().build("/maintenance/activity/CompleteActivity").navigation();
                }

                @Override
                public void onPause(int position) {

                }

                @Override
                public void onContinue(int position) {

                }

                @Override
                public void onSendOrders(int position) {

                }
            }));
            mAdapter.setItems(mItems);
            mRootView.getRecyclerview().setAdapter(mAdapter);
        }
    }

    private void initPtrFrame() {
        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getBacklog();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mParam.page = 0;
                getBacklog();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });
    }

    public void isLogin(){
        if(null == BaseAppConst.accountInfo){
            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_LOGIN);
        }else{
            mParam = new Backlog.ToDoParam(LIMIT, BaseAppConst.accountInfo.getUserId(), BaseAppConst.accountInfo.getCorpId());
            mRootView.getPtrclassicframelayout().autoRefresh();
        }
    }

    /**
     * 获取待办
     */
    private void getBacklog() {
        mModel.getToDo(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<Backlog.ToDo>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<Backlog.ToDo> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                   MyApplication.getInstance().gotoLoginActivity();
                }
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    mRootView.getEmptyLayout().ERROR_TIP = response.getStatuMsg();
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                    return;
                }
                if(response.getData().rows.size() < LIMIT){
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
                }else{
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
                    mParam.page++;
                }

                if(mParam.page == 0){
                    mItems.clear();
                }
                mItems.addAll(response.getData().rows);
                if(mItems.size() == 0){
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
                }else{
                    mRootView.getEmptyLayout().hide();
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
            }
        });
    }

    private AddProgressDialog.Builder addProgressDialog;
    /**
     * 追记弹框
     */
    private void dialogProgress(){
        if(addProgressDialog != null){
            addProgressDialog.show();
        }else{
            addProgressDialog = new AddProgressDialog.Builder(mRootView.getRecyclerview().getContext());
            addProgressDialog.setTitle("追记描述")
            .setListener(new AddProgressDialog.OnClickListener() {
                @Override
                public void onClick(String describe) {
                    addProgressDialog.dismiss();
                }
            })
            .create()
            .show();
        }
        addProgressDialog.clear();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mAdapter = null;
        this.mItems = null;

        this.addProgressDialog = null;

        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(mAppManager.getCurrentActivity().RESULT_OK != resultCode){
            return;
        }
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_MaintainDetails:
                mRootView.getPtrclassicframelayout().autoRefresh();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccess(LoginEvent loginEvent){
        if(!isFirst) {
            isFirst = true;
            initDate();
        }
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void BacklogListRefresh(MaintainDetailsEvent maintainDetailsEvent){
        mRootView.getPtrclassicframelayout().autoRefresh();
    }
}
